<style lang="less">
@import "./../common.less";
</style>
<template>
  <div>
    <!-- 搜索栏 -->
    <Row>
      <Card>
        <Form ref="searchData" :model="searchData" :label-width="100">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="指标搜索" prop="superiorIndexId">
                <Cascader
                  :data="selectIndexType"
                  v-model="searchData.indexSeachVal"
                  change-on-select
                  @on-change="selectIndex"
                ></Cascader>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="责任单位">
                <Select
                  filterable
                  clearable
                  placeholder="请输入责任单位"
                  v-model="searchData.responsibilityUnit"
                  style="width: 150px"
                >
                  <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="牵头单位">
                <Select
                  filterable
                  clearable
                  placeholder="请输入牵头单位"
                  v-model="searchData.leadUnit"
                  style="width: 150px"
                >
                  <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="选择年份">
                <DatePicker
                  type="year"
                  format="yyyy"
                  v-model="searchData.dateTime"
                  @on-change="handlerFormat"
                  placeholder="请选择指标年份"
                  style="width:185px"
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="方向">
                <Select v-model="searchData.direction" placeholder="请选择方向" style="width: 150px">
                  <Option value="+">+</Option>
                  <Option value="-">-</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <FormItem>
              <Button v-if="btnAccess.query" type="primary" @click="seachSubmit(10,1)">提交搜索</Button>
              <Button @click="seachReset('searchData')" style="margin-left: 8px">重置搜索</Button>
            </FormItem>
          </Row>
        </Form>
      </Card>
    </Row>

    <Card title="导出" style="margin-top:10px;">
      <Row class="btnArrs">
        <!-- <Button
          v-if="isSpuerAdmins.query"
          type="success"
          @click="openDownloadModal('1')"
        >导出市对县指标分析报告</Button>-->
        <Button type="success" @click="openDownloadModal('2')">导出市对县汇总表</Button>
      </Row>
    </Card>

    <!-- 指标数据 -->
    <Row style="margin-top:20px">
      <Card>
        <Table stripe border :columns="columns1" :loading="tableLoading" :data="cityIndexList"></Table>
        <div style="margin-top:20px;margin-left:40%">
          <Page
            @on-change="pageNumberChange"
            :current="pageCurrent"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>

    <!-- 填写分数模态框 -->
    <Modal v-model="indexModal" :title="'指标得分填写'" width="900px">
      <div>
        <Form ref="formCityData" :model="formCityData" :rules="regForm" :label-width="100">
          <Row>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="一级指标">
                <Input v-model="formCityData.superiorIndexId" disabled placeholder="指标名称"></Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="权数" :label-width="80">
                <Input v-model="formCityData.weight" disabled placeholder="权数"></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="二级指标">
                <Input v-model="formCityData.indexName" disabled placeholder="二级指标"></Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="标准值" :label-width="80">
                <Input v-model="formCityData.standardValue" disabled placeholder="标准值"></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="牵头单位">
                <Input v-model="formCityData.leadUnitName" disabled placeholder="牵头单位"></Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="责任单位" :label-width="80">
                <Input v-model="formCityData.respUnitName" disabled placeholder="责任单位"></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="得分率" prop="score">
                <InputNumber :max="100" :min="0" v-model="formCityData.score" style="width:auto;"></InputNumber>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="12">
              <FormItem label="排名" prop="rank" :label-width="80">
                <InputNumber :min="1" v-model="formCityData.rank" style="width:auto;"></InputNumber>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :lg="24">
              <FormItem label="进展情况" prop="indexProgress">
                <Input
                  maxlength="500"
                  v-model="formCityData.indexProgress"
                  type="textarea"
                  :autosize="{minRows: 2,maxRows: 5}"
                  placeholder="请输入进展情况(最多输入500字)"
                ></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :lg="24">
              <FormItem label="存在问题" prop="problems">
                <Input
                  maxlength="500"
                  v-model="formCityData.problems"
                  type="textarea"
                  :autosize="{minRows: 2,maxRows: 5}"
                  placeholder="请输入存在问题(最多输入500字)"
                ></Input>
              </FormItem>
            </i-col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button type="success" size="large" :loading="ModalLoading" @click="submitForm">确认提交</Button>
        <Button size="large" @click="closeAudit">取消</Button>
      </div>
    </Modal>

    <!-- 下载模态框 -->
    <Modal
      v-model="downLoadModal"
      :title="downLoadTitle"
      @on-cancel="cancelExportModal"
      width="600px"
    >
      <div>
        <!-- 导出市对县指标分析报告 -->
        <!-- <Row v-if="isIndexAnalysis">
          <i-col :xs="12">
            <DatePicker
              type="month"
              v-model="downloadWordDate"
              @on-change="downloadWord"
              format="yyyyMM"
              placeholder="请选择导出日期(必填)"
              style="width: 200px;"
            ></DatePicker>
          </i-col>
          <i-col :xs="12">
            排名前
            <InputNumber placeholder="(必填)" v-model="topNum" :min="1" style="width:70px;"></InputNumber>名
          </i-col>
        </Row>-->
        <!-- 导出excel汇总表 -->
        <Row v-if="!isIndexAnalysis">
          <i-col :xs="24">
            <DatePicker
              type="month"
              v-model="downloadDate"
              @on-change="getdownbloadDate"
              format="yyyyMM"
              placeholder="请选择导出日期(必填)"
              style="width: 200px;"
            ></DatePicker>
          </i-col>
          <i-col :xs="24" style="margin:10px 0;">* 请选择排序字段</i-col>
          <i-col :xs="24">
            <RadioGroup v-model="orderBy">
              <Radio label="rank">排名</Radio>
              <Radio label="sort">指标序号</Radio>
              <Radio label="departSort">单位排序</Radio>
              <Radio label="finalScore">得分</Radio>
            </RadioGroup>
          </i-col>
        </Row>
      </div>
      <div slot="footer">
        <Button type="success" size="large" :loading="ModalLoading" @click="confirmExport">确认导出</Button>
        <Button size="large" @click="cancelExportModal">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { cityAjax } from "@/api/city";
import { hasOneOf } from "@/libs/tools";
import { URL } from "@/libs/util";
// 以防命名冲突
const HOST = URL;
// 验证0-100数字
const regNumber = new RegExp("^(\\d|[1-9]\\d|100)$");
export default {
  data() {
    const validateScore = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写分数"));
      } else if (!regNumber.test(value)) {
        callback(new Error("0-100范围内"));
      } else {
        callback();
      }
    };
    const validateRank = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请填写排名"));
      } else if (!regNumber.test(value)) {
        callback(new Error("请输入正整数范围内"));
      } else {
        callback();
      }
    };
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      // 是否为超级管理员
      isSpuerAdmins: {
        query: true
      },
      ModalLoading: false, // 模态框Loading
      indexModal: false, // 模态框显示
      tableLoading: true, // 表格loading
      pageTotal: 0, // 总页数
      pageSize: 10, // 页数
      isAuditText: false, // 审核状态 ： 回退时候 Form表单显示内容
      pageNumber: 1, // 页码
      pageCurrent: 1, // 当前页
      selectTime: "", // form表单里月份选择器
      searchData: {
        indexSeachVal: [],
        superiorIndexId: "", // 一级指标
        leadUnit: "", // 牵头单位
        indexName: "", // 二级指标
        responsibilityUnit: "", // 责任单位
        audit: "", // 审核状态
        direction: "", // 方向
        dateTime: "" // 年份
      },
      formCityData: {
        finalScore: null, // 得分
        score: null, // 得分率
        rank: null, // 排名
        superiorIndexId: "", // 一级指标
        leadUnit: "", // 牵头单位code
        leadUnitName: "", // 牵头单位name
        responsibilityUnit: "", // 责任单位code
        respUnitName: "", // 责任单位name
        direction: "", // 方向
        audit: "", // 审核状态
        fristWeight: "", // 一级指标权数
        actualWeight: "", // 实际权数
        weight: "", // 权数
        monthTime: "", // 月份
        dateTime: "", // 年月

        indexProgress: "", // 进展情况
        problems: "" // 存在问题
      },
      cityIndexList: [], // Tabel数据
      selectIndexType: [
        // 搜索指标里的关联指标
        {
          label: "全部",
          value: "全部"
        }
      ],
      isWriteStause: "", // 是否可以填写状态
      regForm: {
        // score: [{ validator: validateScore, trigger: "blur" }],
        rank: [{ validator: validateRank, trigger: "blur" }],
        indexProgress: [
          {
            required: true,
            message: "请输入进展情况",
            trigger: "blur"
          }
        ],
        problems: [
          {
            required: true,
            message: "请输入进展情况",
            trigger: "blur"
          }
        ]
      },
      columns1: [
        {
          title: "序号",
          type: "index",
          width: 80,
          fixed: "left"
        },
        {
          title: "二级指标",
          key: "indexName",
          width: 200,
          fixed: "left"
        },
        {
          title: "时间",
          key: "dateTime",
          width: 120,
          fixed: "left"
        },
        {
          title: "权重",
          width: 100,
          align: "center",
          key: "weight",
          sortable: true
        },
        {
          title: "得分",
          width: 100,
          key: "finalScore",
          sortable: true
        },
        {
          title: "得分率",
          width: 100,
          key: "score",
          sortable: true
        },
        {
          title: "排名",
          width: 100,
          align: "center",
          key: "rank",
          sortable: true
        },
        {
          title: "牵头单位",
          key: "leadUnitName"
          // width: 130
        },
        {
          title: "责任单位",
          key: "respUnitName"
          // width: 130
        },
        {
          title: "状态",
          minWidth: 100,
          maxWidth: 100,
          key: "audit",
          fixed: "right",
          render: (h, params) => {
            const row = params.row;
            var color = "";
            var text = "";
            switch (row.audit) {
              case "1":
                color = "primary";
                text = "已填写";
                break;
              default:
                color = "#9e9e9e";
                text = "未填写";
                break;
            }
            return h(
              "Tag",
              {
                props: {
                  color: color
                }
              },
              text
            );
          }
        },
        {
          title: "操作",
          key: "action",
          minWidth: 100,
          maxWidth: 100,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            var text = "";
            var color = "";
            var isOpen = true;
            if (this.isWriteStause === "0") {
              color = "primary";
              text = "不可填写";
              isOpen = true;
            } else if (this.isWriteStause === "1") {
              text = "填写分数";
              isOpen = false;
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    disabled: isOpen
                  },
                  style: {
                    marginRight: "5px",
                    display: this.btnAccess.add2
                  },
                  on: {
                    click: () => {
                      if (this.isWriteStause === "0") {
                        this.isDrawerShow = false; // 侧边栏不显示
                      } else if (this.isWriteStause === "1") {
                        this.isDrawerShow = true; // 侧边栏显示
                      }
                      this.indexModal = true;
                      // 如果等于3 退回显示内容
                      this.isAuditText =
                        params.row.audit === "3" ? true : false;
                      // 判断是不是有月份 如果没有月份的话为新数据
                      if (params.row.monthTime === "") {
                        this.selectTime = "";
                      } else {
                        var date = [params.row.dateTime, params.row.monthTime];
                        this.selectTime = date.join("-");
                        this.formCityData.dateTime = params.row.dateTime;
                        this.formCityData.monthTime = params.row.monthTime;
                      }

                      //
                      this.formCityData = Object.assign(
                        this.formCityData,
                        params.row
                      );

                      this.formCityData.departcode = params.row.leadUnit;
                      console.log(this.formCityData.departcode);
                      console.log(this.formCityData);
                    }
                  }
                },
                text
              )
            ]);
          }
        }
      ],
      downloadDate: "", // 下载excel日期
      downloadWordDate: "", // 下载word日期
      topNum: null, // 排名前几名
      orderBy: "", // 排名单选框
      downLoadModal: false,
      downLoadTitle: "",
      isIndexAnalysis: false // 是否显示导出指标分析
    };
  },
  methods: {
    // 获取月份
    selectMonth(date) {
      this.selectTime = date;
      var i = date.indexOf("-");
      this.formCityData.dateTime = date.substring(0, i);
      this.formCityData.monthTime = date.substring(i + 1);
    },
    // 获取时间
    handlerFormat(dateTime) {
      this.searchData.dateTime = dateTime;
    },
    // 表格显示条数
    pageSizeChange(size) {
      this.pageSize = size;
      this.tableLoading = true;
      this._getCityList(this.searchData, this.pageSize, this.pageNumber)
        .then(result => {
          // this.pageTotal = parseInt(result.results.pageTotal) * 10;
          this.cityIndexList = result.results.list;
          this.tableLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 页数改变
    pageNumberChange(number) {
      this.pageNumber = number;
      this.pageCurrent = number;
      this.tableLoading = true;
      this._getCityList(this.searchData, this.pageSize, this.pageNumber)
        .then(result => {
          // this.pageTotal = parseInt(result.results.pageTotal) * 10;
          this.cityIndexList = result.results.list;
          this.tableLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 关闭模态框
    closeAudit() {
      this.indexModal = false;
    },
    // 确认提交分数
    submitForm() {
      this.$refs["formCityData"].validate(valid => {
        if (valid) {
          // Loading
          this.ModalLoading = true;
          this._addCityIndex(this.formCityData).then(result => {
            console.log(result);
            if (result.data.code === "200") {
              this.ModalLoading = false;
              this.indexModal = false;
              this.$Message.success("操作成功");
              this._getCityList(this.searchData, this.pageSize, this.pageNumber)
                .then(result => {
                  // this.pageTotal = parseInt(result.results.pageTotal) * 10;
                  this.cityIndexList = result.results.list;
                  this.tableLoading = false;
                })
                .catch(err => {
                  console.log(err);
                });
            } else if (result.data.code === "500") {
              this.ModalLoading = false;
            }
          });
        } else {
          this.$Message.error("请输入完整");
        }
      });
    },
    // 指标管理关联 on-change
    selectIndex(value) {
      if (value[1] !== undefined) {
        this.searchData.indexName = value[1];
      } else {
        this.searchData.superiorIndexId = value[0] === "全部" ? "" : value[0]; // 选择为全部时 是一个空的字符串
        this.searchData.indexName = "";
      }
    },
    // 提交搜索
    seachSubmit(pageSize, pageNumber) {
      this.tableLoading = true;
      this.searchData = Object.assign(this.searchData, {
        leadUnit: this.searchData.leadUnit,
        responsibilityUnit: this.searchData.responsibilityUnit
      });
      this._getCityList(this.searchData, pageSize, pageNumber)
        .then(result => {
          // this.pageTotal = parseInt(result.results.pageTotal) * 10;
          this.cityIndexList = result.results.list;
          this.tableLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 重置搜索
    seachReset(name) {
      this.$refs[name].resetFields();
      this.searchData = {
        superiorIndexId: "", // 一级指标
        leadUnit: "", // 牵头单位
        indexName: "", // 二级指标
        responsibilityUnit: "", // 责任单位
        audit: "", // 审核状态
        direction: "",
        dateTime: "",
        indexSeachVal: []
      };
    },
    // 获取city指标
    _getCityList(form, pageSize, pageNumber) {
      const url = "/countryIndicators/queryInspection";
      const key = "countryIndicatorsFilter";
      let formData = Object.assign(form, {
        pageSize,
        pageNumber
      });
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key }).then(res => {
          if (res.data.code === "200") {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
    // 添加分数、排名
    _addCityIndex(formData) {
      const url = "/countryIndicators/insertScore";
      const key = "countryIndicatorsEntity";
      return new Promise((resolve, reject) => {
        cityAjax({ formData, url, key })
          .then(result => {
            resolve(result);
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // // 打开报送情况页面
    // openSubmitPage() {
    //   this.$router.push({
    //     name: "city_submits"
    //   });
    // },
    // 获取下载时间
    getdownbloadDate(date) {
      this.downloadDate = date;
    },
    // 导出市对县汇总表
    downloadFile() {
      if (this.downloadDate !== "") {
        let times = this.downloadDate;
        let orderBy = this.orderBy;
        window.open(
          HOST +
            "/countryIndicators/exportDate?datetime=" +
            times +
            "&orderBy=" +
            orderBy
        );
        this.downLoadModal = false;
      } else {
        this.$Notice.error({
          title: "请选择导出日期",
          duration: 3.5
        });
      }
    },
    // 获取下载word时间
    downloadWord(date) {
      this.downloadWordDate = date;
    },
    // 导出word 分析报告
    downloadWordFile() {
      if (this.downloadWordDate !== "" && this.topNum !== null) {
        let times = this.downloadWordDate;
        let topNum = this.topNum;
        window.open(
          HOST +
            "/countryIndicators/cityIndexReport?datetime=" +
            times +
            "&topNum=" +
            topNum
        );
        this.downLoadModal = false;
      } else {
        this.$Notice.error({
          title: "请选择导出日期 或者 导出排名",
          duration: 3.5
        });
      }
    },
    /**
     *打开导出模态框
     * @param {*} value  1：导出市对县指标分析报告  2：导出市对县汇总表
     *
     */
    openDownloadModal(value) {
      this.downLoadModal = true;
      if (value === "1") {
        this.downLoadTitle = "导出市对县指标分析报告";
        this.isIndexAnalysis = true;
      } else {
        this.downLoadTitle = "导出市对县汇总表";
        this.isIndexAnalysis = false;
      }
    },
    // 确认导出
    confirmExport() {
      if (this.isIndexAnalysis) {
        this.downloadWordFile();
      } else {
        this.downloadFile();
      }
    },
    // 关闭导出模态框
    cancelExportModal() {
      this.downLoadModal = false;
      // 清空下载模态框的值
      this.downloadWordDate = "";
      this.downloadDate = "";
      this.topNum = null;
      this.orderBy = "";
    }
  },
  created() {
    this._getCityList(this.searchData, this.pageSize, this.pageNumber)
      .then(result => {
        console.log(result);
        this.isWriteStause = result.results.status; // 是否可以填写状态
        // seach指标搜索 组件 需要的数据格式
        var indexList = result.results.indexMap;
        indexList.forEach(list => {
          let children = [];
          if (list.secondIndex !== undefined) {
            list.secondIndex.forEach(item => {
              let listChild = Object.assign(
                {},
                {
                  label: item.indexName,
                  value: item.indexName
                }
              );
              children.push(listChild);
            });
          }
          let data = Object.assign(
            {},
            {
              label: list.firstName.indexName,
              value: list.firstName.id,
              children
            }
          );
          this.selectIndexType.push(data);
        });
        // this.pageTotal = parseInt(result.results.pageTotal) * 10; // 总页数
        this.cityIndexList = result.results.list;
        this.tableLoading = false;
      })
      .catch(err => {
        console.log(err);
      });

    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
    // 获取是否为超级管理员权限
    let isSuperAdmin = sessionStorage.getItem("isSuperAdmin");
    this.globalFunction2(isSuperAdmin);
  },
  watch: {
    selectIndexType: {
      handler(newVal) {
        this.selectIndexType = newVal;
      },
      deep: true
    }
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    },
    access() {
      return this.$store.state.user.access;
    },
    // 管理员
    accessAdmin() {
      return hasOneOf(["admin"], this.access);
    },
    // 责任人
    accessRespons() {
      return hasOneOf(["responsible"], this.access);
    },
    // 经办人
    accessAgent() {
      return hasOneOf(["agent"], this.access);
    }
    //
  }
};
</script>

<style>
.ivu-input-number-disabled .ivu-input-number-input {
  color: #333;
}
.btnArrs button {
  margin: 10px 5px;
}
</style>
